package cii_lib_graph;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.BitSet;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.BoxLayout;
import javax.swing.ButtonModel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.border.BevelBorder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cii_functions.FCII_interfaceReader;
import cii_lib.CCII_ACCESS_INTERF;
import cii_lib.CCII_COMPONENT;
import cii_lib.CIIdata;
import cii_lib.CIIlib;
import cii_lib_graph.elements.GciiToggleButton;

/**
 * This code was edited or generated using CloudGarden's Jigloo SWT/Swing GUI
 * Builder, which is free for non-commercial use. If Jigloo is being used
 * commercially (ie, by a corporation, company or business for any purpose
 * whatever) then you should purchase a license for each developer using Jigloo.
 * Please visit www.cloudgarden.com for details. Use of Jigloo implies
 * acceptance of these licensing terms. A COMMERCIAL LICENSE HAS NOT BEEN
 * PURCHASED FOR THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED LEGALLY FOR
 * ANY CORPORATE OR COMMERCIAL PURPOSE.
 */
public class GCII_BITSGroup {

	private static final Logger log = LoggerFactory
			.getLogger(GCII_BITSGroup.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 3912280692828991987L;

	/**
	 * Buttons group elements
	 */
	private Vector<GciiToggleButton> bitsTB = new Vector<GciiToggleButton>();

	private Vector<GInterfaceTerminal> iTers = new Vector<GInterfaceTerminal>();

	private JTextField valueTxt;

	private JPanel bitsGroupPanel;

	private Rectangle groupBounds = new Rectangle(0, 0, 14, 21);

	private int groupWidth = 0;

	private double bitsValue = 0L;

	private JMenuItem jMenuItem1, jMenuItem2;

	private JPopupMenu jPopupMenu1;

	private CCII_COMPONENT comp = null;

	private BitSet bitsSet = new BitSet();

	private JScrollPane bitsScrollPane;

	public BitSet getBitsSet() {
		return bitsSet;
	}

	public void setBitsSet(BitSet bitsSet) {
		this.bitsSet = bitsSet;
	}

	public GCII_BITSGroup() {
		super();
		initGUI(null);
	}

	public GCII_BITSGroup(CCII_COMPONENT comp) {
		super();
		initGUI(comp);
		this.comp = comp;
	}

	public GCII_BITSGroup(CCII_COMPONENT comp, String xmlModel) {
		super();
		initGUI(comp);
		this.comp = comp;

	}

	/**
	 * INFO: Dodaje butony lokalnie, dla metody getDefaultPanel(); ktora
	 * wyswietli buttonsGroup oraz pole tekstowe
	 * 
	 */
	protected void addBitToggleButton(final CCII_ACCESS_INTERF cix) {
		final GciiToggleButton tmp = new GciiToggleButton();
		final int alreadyHave = bitsTB.size();
		{
			bitsGroupPanel.add(tmp);
			tmp.setContent(cix.GetItem());
			tmp.setText("0");
			setComponentPopupMenu(tmp, jPopupMenu1);
			tmp.setBounds((groupBounds.width * alreadyHave) + groupBounds.x,
					groupBounds.y, groupBounds.width, groupBounds.height);
			tmp.setFont(new java.awt.Font("Tahoma", 0, 11));
			tmp.setAlignmentY(0.5f);
			tmp.setMargin(new java.awt.Insets(0, 0, 0, 0));
			tmp.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent evt) { 
					// tmp.setSelected(tmp.isSelected());
					try {
						if (tmp.getText().equals("1")) {
							// if (!cix.SaveWrite(0, 0, new CIIdata(1,0)))
							// return;
							cix.Write(0, 0, new CIIdata(1, 0));
							countValue(alreadyHave, false, valueTxt);
							tmp.setText("0");
						} else {
							// if (!cix.SaveWrite(0, 0, new CIIdata(1,1)))
							// return;
							cix.Write(0, 0, new CIIdata(1, 1));
							countValue(alreadyHave, true, valueTxt);
							tmp.setText("1");
						}
					} catch (Exception e) {
						log.debug("exc during write: " + e);
					}
					tmp.setPosition(alreadyHave);
					Vector<GciiToggleButton> v = getBitsButtons();
					StringBuilder builder = new StringBuilder();
					for (int i = 0; i < v.size(); i++) {
						builder.append(v.get(i).isSelected() ? "1 " : "0 ");
					}
					log.info("Command: Bit buttons {} value {}", new Object[] {builder, getValueTxt().getText()});
				}
			});
		}
		bitsTB.addElement(tmp);
		groupWidth = alreadyHave + 1;
	}

	public double countValue(int pos, boolean val, JTextField valfield) {
		if (val) {
			bitsValue = bitsValue + Math.pow(2, pos);
		} else {
			bitsValue = bitsValue - Math.pow(2, pos);
		}
		if (bitsValue < 0) {
			valfield.setText("" + (long) bitsValue);
			return 0;
		} else {
			valfield.setText("" + (long) bitsValue);
			return bitsValue;
		}
	}

	public void positionsToEnable(long val) {
		CIIdata tmp = new CIIdata(groupWidth, val);
		String war = tmp.GetBin0();
		boolean accessible = true;
		for (int i = 0; i < groupWidth; i++) {
			if (!bitsTB.get(i).isEnabled())
				accessible = false;
		}
		log.debug(Boolean.toString(accessible));
		bitsValue = val;
		// if (accessible) {
		for (int i = 0; i < groupWidth; i++) {
			ButtonModel buttonModel = bitsTB.get(i).getModel();
			getValueTxt().setForeground(new Color(0, 0, 0));
			if (war.substring(groupWidth - 1 - i, groupWidth - i).equals("0")) {
				bitsTB.get(i).setText("0");
				buttonModel.setSelected(false);
			} else {
				bitsTB.get(i).setText("1");
				buttonModel.setSelected(true);
			}
		}
		// } else {
		// log.debug("Unable to comply - not accessible interface");
		// getValueTxt().setForeground(new Color(255,0,0));
		// }
	}

	public void addBITSInterface(CCII_ACCESS_INTERF arg) {

	}

	private void initGUI(CCII_COMPONENT in) {
		int bitsInterfaces = 0;
		if (in != null) {
			if (getBitsGroupPanel() == null) {
				{
					bitsGroupPanel = new JPanel();
					bitsGroupPanel.setBorder(BorderFactory
							.createEtchedBorder(BevelBorder.LOWERED));
					bitsGroupPanel.setLayout(null);
				}
				{
					jPopupMenu1 = new JPopupMenu();
					// setComponentPopupMenu(bitsGroupPanel, jPopupMenu1);
					{
						jMenuItem1 = new JMenuItem();
						jPopupMenu1.add(jMenuItem1);
						jMenuItem1.setText("Read");
						jMenuItem1.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								log.info("Command: {}", evt.getActionCommand());
								readEnable();
								log.debug(jPopupMenu1.getActionMap().toString());

							}
						});
					}
					{
						jMenuItem2 = new JMenuItem();
						jPopupMenu1.add(jMenuItem2);
						jMenuItem2.setText("Write");
						jMenuItem2.addActionListener(new ActionListener() {
							public void actionPerformed(ActionEvent evt) {
								log.info("Command: {}", evt.getActionCommand());
								log.debug(jPopupMenu1.getActionMap().toString());

							}
						});
					}
				}
			}
			bitsSet = new BitSet(in.getInterfaces().size());
			for (int i = 0; i < in.getInterfaces().size(); i++) {
				if (in.getInterfaces().get(i).GetItem().Type == CIIlib.TABLE_TYPE.BITS) {
					bitsSet.set(bitsInterfaces, false);
					bitsInterfaces++;
					addBitToggleButton(in.getInterfaces().get(i));
					addInterfaceTerminal(in.getInterfaces().get(i));
				}
			}
		}
		int valtxtX = 0;
		int valtxtY = groupBounds.y;
		try {
			// setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			// getContentPane().setLayout(null);
			// getContentPane().add(bitsGroupPanel);
			{
				valtxtX = groupBounds.x + (groupBounds.width * bitsTB.size())
						+ 5;
			}
			{
				valueTxt = new JTextField();
				bitsGroupPanel.add(valueTxt);
				valueTxt.setText("0");
				valueTxt.setBounds(valtxtX, valtxtY, 50, groupBounds.height);
				valueTxt.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) { log.info("Command: {}", evt.getActionCommand());
						long tmp = 0;
						try {
							tmp = new Long(valueTxt.getText());
						} catch (Exception e) {
							// TODO: handle exception
							log.debug(e.toString());
						}
						positionsToEnable(tmp);
					}
				});
			}
			bitsGroupPanel.setBounds(groupBounds.x, groupBounds.y, valtxtX
					+ valueTxt.getWidth(), groupBounds.height + 1);
		} catch (Exception e) {
			log.error("", e);
		}
	}

	public void addInterfaceTerminal(CCII_ACCESS_INTERF cint) {
		GInterfaceTerminal tmp = new GInterfaceTerminal(cint);
		tmp.getWRButton().setVisible(false);
		tmp.getAdressTextField().setVisible(false);
		if (cint.GetItem().Access == CIIlib.TABLE_ACCESS.RO) {
			tmp.getWriteTextField().setVisible(false);
			tmp.getWriteButton().setVisible(false);
		}
		// tmp.setPreferredSize(new Dimension(tmp.getWidthElements(),21));
		iTers.add(tmp);
		tmp = null;
	}

	public JScrollPane getBITPanelExtended() {
		JPanel jPanel1;
		JSeparator jSeparator1;
		{
			bitsScrollPane = new JScrollPane();
			// getContentPane().add(bitsScrollPane);
			// bitsScrollPane.setBounds(602, 112, 287, 238);
			{
				jPanel1 = new JPanel();
				BoxLayout jPanel1Layout = new BoxLayout(jPanel1,
						javax.swing.BoxLayout.Y_AXIS);
				jPanel1.setLayout(jPanel1Layout);
				bitsScrollPane.setViewportView(jPanel1);
				// jPanel1.setPreferredSize(new java.awt.Dimension(462, 167));
				for (int i = 0; i < iTers.size(); i++) {
					jPanel1.add(iTers.get(i));
					jSeparator1 = new JSeparator();
					jPanel1.add(jSeparator1);
				}
			}
		}
		return bitsScrollPane;
	}

	public Rectangle getGroupPosition() {
		return groupBounds;
	}

	public void setGroupPosition(Rectangle groupBounds) {
		this.groupBounds = groupBounds;
	}

	public JTextField getValueTxt() {
		return valueTxt;
	}

	public void setValueTxt(JTextField valueTxt) {
		this.valueTxt = valueTxt;
	}

	public JPanel getBitsGroupPanel() {
		return bitsGroupPanel;
	}

	public void setBitsGroupPanel(JPanel bitsGroupPanel) {
		this.bitsGroupPanel = bitsGroupPanel;
	}

	/**
	 * Auto-generated method for setting the popup menu for a component
	 */
	private void setComponentPopupMenu(final java.awt.Component parent,
			final javax.swing.JPopupMenu menu) {
		parent.addMouseListener(new java.awt.event.MouseAdapter() {
			public void mousePressed(java.awt.event.MouseEvent e) {
				if (e.isPopupTrigger())
					menu.show(parent, e.getX(), e.getY());
			}

			public void mouseReleased(java.awt.event.MouseEvent e) {
				if (e.isPopupTrigger())
					menu.show(parent, e.getX(), e.getY());
			}
		});
	}
	
	private void readEnable() {
		for (GInterfaceTerminal terminal : iTers) {
		log.debug("![s "+terminal.getInterface().Name());
		Runnable readerC = new FCII_interfaceReader(terminal,670);
		Thread thCount = new Thread(readerC);
		thCount.start();
		}
		
	}

	public Vector<GciiToggleButton> getBitsButtons() {
		return bitsTB;
	}
}
